--- title: "2240. Number of Ways to Buy Pens and Pencils" created: 2025-12-20 --- # 2240. Number of Ways to Buy Pens and Pencils **📑 目录** **(Ctrl+点击跳转)** - [题目 2240. Number of Ways to Buy Pens and Pencils](#toc-1766820209831-0) - [思路分析](#toc-1766820209832-1) - [代码实现](#toc-1766820209832-2) - [同类题型](#toc-1766820209832-3) - [视频讲解](#toc-1766820209832-4) ## 题目 [**2240. Number of Ways to Buy Pens and Pencils**](https://leetcode.com/problems/number-of-ways-to-buy-pens-and-pencils/) ![[image-0264fa6c.png]] ## 思路分析 ![[image-5bfe7047.png]] ## 代码实现 ```java class Solution { public long waysToBuyPensPencils(int total, int cost1, int cost2) { long counts=0; for(int i=0;1L*i*cost1<=total;i++){ long rem = total-(1L*i*cost1); counts+=rem/cost2+1; } return counts; } } ``` ```java class Solution { public long waysToBuyPensPencils(int total, int cost1, int cost2) { int maxv=Math.max(cost1,cost2); int minv=Math.min(cost1,cost2); long counts=0; int n=total/maxv; for(int i=0;i<=n;i++){ counts+=(total-maxv*i)/minv+1; } return counts; } } ``` ## 同类题型 ## 视频讲解